# coding=utf-8
# ! /usr/bin/env python
import os
from utils.sendReportEmail import send_report_email
from models.conn_mongo import conn_mongo


class jian_kong(object):
    def get_file_name(self, file_dir):
        """
        传入文件夹路径，获得文件夹下所有非文件夹文件的路径,并且按照时间顺序给他排序
        :param file_dir: 文件夹路径
        :return: file_path_list：文件夹中文件的绝对路径列表,并且结果是按时间从小到大排序的
        """
        for dirpath, dirnames, filenames in os.walk(file_dir):
            file_path_list = []
            # 按时间排序
            file_name_list = sorted(filenames, key=lambda x: os.path.getmtime(os.path.join(file_dir, x)))
            for i in file_name_list:
                file_path_list.append(file_dir + i)
            return file_path_list

    def get_lines_counts(self, file_path_list):
        """
        输入文件的路径，获得文件的最后一行和文件内的总行数
        :param file_path_list: 文件绝对路径的列表
        :return: count:文件总行数，line：文件最后一行
        """

        lines = open(file_path_list[-1], "r").readlines()
        if lines:
            count = len(lines)
            line = lines[-1]
            return [count, line]
        return None

    def get_mail_receiver(self):
        mail_namelist = []
        client = conn_mongo()
        r = client.ob_test.email_recicer.find()
        for i in r:
            mail_namelist.append(i['mailAddress'])
        return mail_namelist

    def check(self):
        file_dir = 'data/logs/'
        count = 0
        while 1:
            file_path_list = self.get_file_name(file_dir)
            counts_lines_list = self.get_lines_counts(file_path_list)
            receiver_mail_list = self.get_mail_receiver()
            # 获取邮件接受者列表
            if receiver_mail_list:
                if counts_lines_list:
                    if count < counts_lines_list[0]:
                        count = counts_lines_list[0]
                        username = '1170926392@qq.com'
                        password = 'gkysxyyisfdzgdcc'
                        receiver_list = receiver_mail_list
                        title = '服务器错误警告'
                        content = counts_lines_list[-1]
                        send_report_email(username, password, receiver_list, title, content, attachment=None)


JianKong = jian_kong()
